import random
import mysql.connector
from mysql.connector import Error
from data_processing import DataProcessor
from behavior_analysis import BehaviorAnalyzer
from rfm_analysis import RFMAnalyzer
from prediction_model import PredictionModel
from dashboard import Dashboard
# 移除文件缓存清理相关代码

def clear_expired_cache(db_config, days=7):
    """清理指定天数前的缓存数据"""
    try:
        connection = mysql.connector.connect(** db_config)
        if connection.is_connected():
            cursor = connection.cursor()
            query = f"""
            DELETE FROM data_cache 
            WHERE updated_at < DATE_SUB(CURDATE(), INTERVAL {days} DAY)
            """
            cursor.execute(query)
            connection.commit()
            print(f"已清理{days}天前的缓存数据")
    except Error as e:
        print(f"清理缓存失败: {e}")
    finally:
        if 'connection' in locals() and connection.is_connected():
            cursor.close()
            connection.close()

def main():
    # 数据库配置
    db_config = {
        'host': 'localhost',
        'user': 'root',
        'password': '123456',  # 替换为你的数据库密码
        'database': 'user_behavior',
        'port': 3306
    }

    # 清除过期缓存
    clear_expired_cache(db_config)

    # 从数据库加载数据
    print("正在从数据库加载数据...")
    data_processor = DataProcessor(db_config)

    # 初始化分析器
    print("正在进行分析器初始化...")
    behavior_analyzer = BehaviorAnalyzer(data_processor)
    rfm_analyzer = RFMAnalyzer(data_processor)
    prediction_model = PredictionModel(data_processor)

    # 预测模型
    print("\n正在训练预测模型...")
    purchase_ranking = prediction_model.train_purchase_intention_model()
    print(f"用户购买概率排行榜:\n{purchase_ranking.head()}")

    # 构建推荐系统
    print("\n正在构建推荐系统...")
    recommendation_model = prediction_model.build_recommendation_model()

    # 从数据中随机选择一个用户ID
    sampled_user_ids = prediction_model.sample_data['user_id'].unique()
    if len(sampled_user_ids) > 0:
        random_user_id = random.choice(sampled_user_ids)
        # 为随机选择的用户生成推荐
        recommendations = prediction_model.get_recommendations(random_user_id)
        print(f"为用户 {random_user_id} 生成的推荐:\n{recommendations}")
    else:
        print("数据中没有可用的用户ID。")

    # 启动仪表盘
    print("\n正在启动仪表盘...")
    dashboard = Dashboard(data_processor, behavior_analyzer, rfm_analyzer, prediction_model)
    dashboard.run(debug=False)

if __name__ == "__main__":
    main()